import React, { useEffect, useRef, useState } from "react";

import { Header } from "./Header";
import "./page.css";
import {
  Button,
  Form,
  FormInstanceFunctions,
  Input,
  MessagePlugin,
} from "tdesign-react";
import EncryptUtil from "utils/EncryptUtil";
import { ApiAuth } from "_common/api/auth";
import axiosDefault from "utils/defaultAxios";
import { LoginForm } from "_common/DataType";

type User = {
  name: string;
};

export const Page: React.FC = () => {
  const [user, setUser] = React.useState<User>();
  const [, setToken] = useState<string>("");
  const formRef = useRef<FormInstanceFunctions>();
  const apiAuth = new ApiAuth(axiosDefault);
  const [logined, setLogined] = useState<boolean>();
  const { FormItem } = Form;
  useEffect(() => {
    setToken(localStorage.getItem("tokenKey") || "");
    const loginInfo = localStorage.getItem("loginInfo");
    if (loginInfo) {
      setUser(JSON.parse(loginInfo));
      setLogined(true);
    } else {
      setLogined(false);
    }
    formRef.current?.setFieldsValue({
      account: "superAdmin",
      password: "1q2w3e*",
    });
  }, []);
  return (
    <article>
      <Header
        user={user}
        onLogin={() => setUser({ name: "Jane Doe" })}
        onLogout={() => {
          setUser(undefined);
          setToken("");
          localStorage.removeItem("tokenKey");
          localStorage.removeItem("loginInfo");
          setLogined(false);
        }}
        onCreateAccount={() => setUser({ name: "Jane Doe" })}
      />
      <section className="storybook-page gap-3">
        {/*  <Textarea
          placeholder="请输入token"
          onChange={setToken}
          value={token}
          rows={10}
        />
        <Button
          onClick={() => {
            localStorage.setItem("tokenKey", token);
            MessagePlugin.success("设置成功");
          }}
        >
          设置token
        </Button> */}
        {logined ? (
          <div className="w-full text-center">
            <h3 className="text-3xl">已登录</h3>
          </div>
        ) : (
          <Form
            ref={formRef}
            onSubmit={async () => {
              try {
                const formValue = formRef.current?.getFieldsValue?.(true) || {};
                if (formValue.account === "" || formValue.password === "") {
                  MessagePlugin.error("请输入用户名和密码");
                  return false;
                }
                const data = {
                  account: formValue.account,
                  password: EncryptUtil.encryptToSm2(formValue.password),
                };
                const response = await apiAuth.login(data as LoginForm);
                if (response && response.code == 200 && response.data) {
                  console.log("response", response.data);
                  setToken(response.data.token);
                  MessagePlugin.success("登录成功");
                  localStorage.setItem(
                    "loginInfo",
                    JSON.stringify(response.data)
                  );
                  setUser({ name: response.data.name ?? "" });
                  setLogined(true);
                }
                /* const response = await apiLogin.login(data as LoginForm);
              if (response && response.code && response.data) {
                // 登录成功
                dispatch(login(response.data));
                MessagePlugin.success("登录成功");
                // 获取用户基本信息，包括权限等
                if (Object.keys(userState).length === 0) {
                  // 获取用户信息
                  dispatch(getUserInfo());
                }
                navigate("/");
              } */
              } catch (e) {
                MessagePlugin.error("登录失败");
              }
            }}
          >
            <p className="text-2xl mt-5 mb-3 text-success-600 text-center">
              登 录
            </p>
            <div className="">
              <FormItem
                labelWidth={0}
                name="account"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input
                  placeholder="用户名"
                  size="small"
                  className="cus-input"
                />
              </FormItem>
            </div>
            <div className="">
              <FormItem
                labelWidth={0}
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input
                  placeholder="密码"
                  size="small"
                  type="password"
                  style={{ backgroundColor: "transparent" }}
                />
              </FormItem>
            </div>
            <div className="">
              <Button className="btn  success sm w-full" type="submit">
                登&nbsp;&nbsp;&nbsp;&nbsp;录
              </Button>
            </div>
          </Form>
        )}
      </section>
    </article>
  );
};
